package com.cloud.school.bus.teacherhelper.modules.notice;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.ErrorExceptionHandler;
import com.android.support.jhf.network.IErrorListener;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.android.support.jhf.universalimageloader.core.ImageLoader;
import com.android.support.jhf.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.android.support.jhf.utils.ImageUtil;
import com.cloud.school.bus.teacherhelper.R;
import com.cloud.school.bus.teacherhelper.base.activity.BaseActivity;
import com.cloud.school.bus.teacherhelper.base.dialog.CustomAlertDialog;
import com.cloud.school.bus.teacherhelper.base.uploadpic.UploadPic;
import com.cloud.school.bus.teacherhelper.base.uploadpic.UploadPic.OnGetPicSucceed;
import com.cloud.school.bus.teacherhelper.base.utils.PictureUtil;
import com.cloud.school.bus.teacherhelper.base.view.TitleNavBarView;
import com.cloud.school.bus.teacherhelper.entitys.Student;
import com.cloud.school.bus.teacherhelper.modules.notice.adapter.StuSelectAdapter;
import com.cloud.school.bus.teacherhelper.protocol.notice.SendNoticeRequest;
import com.cloud.school.bus.teacherhelper.protocol.notice.SendNoticeResponse;

/**
 * 发布家长通知
 * 
 * @author lenovo
 * 
 */
public class ParentNoticeActivity extends BaseActivity {

	private EditText mTitleEditText;
	private EditText mContentEditTextview;
	private TextView mInputLenghtTextView;
	private ImageView mUploadImageView;
	private ViewGroup mUploadLayout;
	private GridView mGridView;
	private StuSelectAdapter mStuSelectAdapter;

	private UploadPic mUploadPic;
	/** 是否回执0否1是 */
	private int mIsconfirm = 0;
	private String mPicPathString;
	private int mRequestCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activit_parent_notice);

		init();
	}

	@Override
	protected void init() {

		mUploadPic = new UploadPic(this);

		mUploadLayout = (ViewGroup) findViewById(R.id.uploadLayout);
		mUploadImageView = (ImageView) findViewById(R.id.uploadImageView);
		mUploadImageView.setVisibility(View.GONE);
		mTitleEditText = (EditText) findViewById(R.id.titleEditText);
		mContentEditTextview = (EditText) findViewById(R.id.contentEditText);
		mInputLenghtTextView = (TextView) findViewById(R.id.inputLenghtTextView);
		setInputLenght(0);

		mGridView = (GridView) findViewById(R.id.gridView);
		mStuSelectAdapter = new StuSelectAdapter(mContext,
				mApplication.mStudentList);
		mStuSelectAdapter.clearSelected();
		mGridView.setAdapter(mStuSelectAdapter);

		setListener();
		setTitleNavBar();
	}

	private void setInputLenght(int inputLenght) {
		if (0 == inputLenght) {
			mInputLenghtTextView.setVisibility(View.GONE);
		} else {
			mInputLenghtTextView.setVisibility(View.VISIBLE);
			// mInputLenghtTextView.setText("已输入" + inputLenght + "字");
			mInputLenghtTextView.setText(getString(R.string.entered_x_words)
					.replace("%@", inputLenght + ""));
		}
	}

	@Override
	protected void setListener() {

		mContentEditTextview.setFilters(new InputFilter[] { new InputFilter() {

			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {

				if (source.equals("\n")) {
					return "";
				}
				return source;
			}

		} });

		mTitleEditText.setFilters(new InputFilter[] { new InputFilter() {

			@Override
			public CharSequence filter(CharSequence source, int start, int end,
					Spanned dest, int dstart, int dend) {

				if (source.equals("\n")) {
					return "";
				}
				return source;
			}

		} });

		mUploadPic.setOnGetPicSucceed(new OnGetPicSucceed() {

			@Override
			public void onGetPicSucceed(String picPathString, int requestCode) {
				mRequestCode = requestCode;
				uploadPic(picPathString);
			}
		});

		Button uploadPicButton = (Button) findViewById(R.id.uploadPicButton);
		uploadPicButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				mUploadPic.doPickPhotoAction();
			}
		});

		mContentEditTextview.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				setInputLenght(arg0.length());
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {

			}
		});

		mContentEditTextview
				.setOnFocusChangeListener(new OnFocusChangeListener() {

					@Override
					public void onFocusChange(View arg0, boolean arg1) {
						if (arg1) {
							mUploadLayout.setVisibility(View.VISIBLE);
						} else {
							mUploadLayout.setVisibility(View.GONE);
						}
					}
				});
	}

	@Override
	protected void setTitleNavBar() {
		TitleNavBarView titleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		titleNavBarView.setMessage(getString(R.string.send_notice));
		titleNavBarView.setLeftButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// finish();
				cancel(true);
			}
		});
		titleNavBarView.setRightButtonImageString(
				R.drawable.btn_send_notice_xml, "", R.color.text_blue);
		titleNavBarView.setRightButtonOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				StringBuilder stringBuilder = new StringBuilder();
				if (checkSubmit(stringBuilder)) {
					// HandlerToastUI.getHandlerToastUI(mContext, "提交成功");
					isconfirmDialog();
				} else {
					HandlerToastUI.getHandlerToastUI(mContext,
							stringBuilder.toString());
				}
			}
		});
	}

	private void isconfirmDialog() {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog
				.setTitleMessage(getString(R.string.tips), Color.BLACK);
		customAlertDialog
				.setMessage(getString(R.string.the_notice_requires_parents_to_confirm_it));
		customAlertDialog.setLeftButton(getString(R.string.yes),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						mIsconfirm = 1;
						sendNotice();
					}
				});
		customAlertDialog.setRightButton(getString(R.string.no),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						mIsconfirm = 0;
						sendNotice();
					}
				});
		customAlertDialog.show();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (null != mUploadPic) {
			mUploadPic.onActivityResult(requestCode, resultCode, data);
		}
	}

	private void uploadPic(String picPathString) {
		mPicPathString = picPathString;
		ImageLoader.getInstance().displayImage(
				Uri.decode(Uri.fromFile(new File(picPathString)).toString()),
				mUploadImageView, mApplication.mNoCacheDisplayImageOptions,
				new SimpleImageLoadingListener() {
					@Override
					public void onLoadingComplete(String imageUri, View view,
							Bitmap loadedImage) {
						mUploadImageView.setVisibility(View.VISIBLE);

						if (imageUri.startsWith("http://")) {
							mUploadImageView.setImageBitmap(loadedImage);
						} else if (imageUri.startsWith("file:///")) {
							ImageUtil.setRotaingImageBitmap(
									imageUri.replace("file:///", "/"),
									loadedImage, mUploadImageView);
						} else {
							ImageUtil.setRotaingImageBitmap(imageUri,
									loadedImage, mUploadImageView);
						}

					}
				});
	}

	private boolean checkSubmit(StringBuilder stringBuilder) {
		stringBuilder.delete(0, stringBuilder.length());
		if (TextUtils.isEmpty(mContentEditTextview.getText().toString())) {
			stringBuilder.append(getString(R.string.notice_content));
			return false;
		}
		// 请选择学生
		int i = 0;
		for (i = 1; i < mStuSelectAdapter.getCount(); i++) {
			Student student = (Student) mStuSelectAdapter.getItem(i);
			if (student.isSelected) {
				break;
			}
		}
		if (i == mStuSelectAdapter.getCount()) {
			stringBuilder.append(getString(R.string.please_select_students));
			return false;
		}

		return true;
	}

	private void sendNotice() {
		StringBuilder studentIdStringBuilder = new StringBuilder();
		for (int i = 1; i < mStuSelectAdapter.getCount(); i++) {
			Student student = (Student) mStuSelectAdapter.getItem(i);
			if (student.isSelected) {
				studentIdStringBuilder.append(student.studentid).append(",");
			}
		}
		studentIdStringBuilder.delete(studentIdStringBuilder.length() - 1,
				studentIdStringBuilder.length());

		String fname = null, fsize = null, fbody = null, fext = null;
		if (!TextUtils.isEmpty(mPicPathString)) {
			fbody = PictureUtil.getPicString(mPicPathString, 512);
			fext = mPicPathString
					.substring(mPicPathString.lastIndexOf(".") + 1);
			fname = mPicPathString
					.substring(mPicPathString.lastIndexOf("/") + 1);
			fsize = fbody.length() + "";
		}
		String titleString = "";
		if (TextUtils.isEmpty(mTitleEditText.getText().toString())) {
			if (mContentEditTextview.getText().toString().length() <= 10) {
				titleString = mContentEditTextview.getText().toString();
			} else {
				titleString = mContentEditTextview.getText().toString()
						.substring(0, 10);
			}
		} else {
			titleString = mTitleEditText.getText().toString();
		}

		NetworkClient.getNetworkClient().PostRequest(
				new SendNoticeRequest(mContext, titleString,
						mContentEditTextview.getText().toString(),
						studentIdStringBuilder.toString(), mIsconfirm + "",
						fname, fsize, fbody, fext), new SendNoticeResponse() {
					@Override
					public void onResponse(
							ResponseHandlerInterface responseHandlerInterface) {
						if ("1".equals(code)) {
							HandlerToastUI.getHandlerToastUI(mContext,
									getString(R.string.send_succeed));
							setResult(RESULT_OK);
							// finish();
							cancel(false);

						}
					}
				}, null, new IErrorListener() {

					@Override
					public void onFailure(int statusCode, Header[] headers,
							byte[] responseBody, Throwable error) {
						if (mContext instanceof Activity) {
							StringBuffer stringBuffer = new StringBuffer();
							ErrorExceptionHandler.NetworkExceptionHandler(
									stringBuffer, error);
							if (!TextUtils.isEmpty(stringBuffer.toString())) {
								HandlerToastUI.getHandlerToastUI(mContext,
										stringBuffer.toString());
							}
						}
						if (UploadPic.PHOTO_PICKED_WITH_DATA == mRequestCode) {
							mUploadPic.removePicture(mPicPathString);
						}
					}
				});
	}

	private void cancelDialog(final OnClickListener onClickListener) {
		CustomAlertDialog customAlertDialog = new CustomAlertDialog(mContext,
				R.style.CustomAlertDialog);
		customAlertDialog
				.setTitleMessage(getString(R.string.tips), Color.BLACK);
		customAlertDialog
				.setMessage(getString(R.string.cancel_sending_the_notice));
		customAlertDialog.setLeftButton(getString(R.string.yes),
				new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (null != onClickListener) {
							onClickListener.onClick(arg0);
						}
					}
				});
		customAlertDialog.setRightButton(getString(R.string.no),
				new OnClickListener() {

					@Override
					public void onClick(View v) {

					}
				});
		customAlertDialog.show();
	}

	/**
	 * 返回
	 * 
	 * @param isShowCancelDialog
	 *            true判断标题和内容不为空按下返回键提示对话框
	 */
	private void cancel(boolean isShowCancelDialog) {
		if (isShowCancelDialog && (!TextUtils.isEmpty(mTitleEditText.getText().toString())
				|| !TextUtils.isEmpty(mContentEditTextview.getText()
						.toString()))) {
				cancelDialog(new OnClickListener() {

					@Override
					public void onClick(View arg0) {
						if (UploadPic.PHOTO_PICKED_WITH_DATA == mRequestCode) {
							mUploadPic.removePicture(mPicPathString);
						}
						finish();
					}
				});
		} else {
			if (UploadPic.PHOTO_PICKED_WITH_DATA == mRequestCode) {
				mUploadPic.removePicture(mPicPathString);
			}
			finish();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			cancel(true);
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
}
